// 购物车页面逻辑
Page({
  data: {
    cartItems: [],
    selectAll: true,
    totalPrice: 0,
    selectedCount: 0
  },

  onLoad() {
  },

  onShow() {
    this.loadCartData();
  },

  // 加载购物车数据
  loadCartData() {
    const token = wx.getStorageSync('token');
    const userid = wx.getStorageSync('userid');
    wx.request({
      url: 'http://47.94.6.186:3001/api/cart/list',
      method:'POST',
      data:{userid:userid},
      header: {
        'Content-Type': 'application/json',
        'token': token // 添加token到请求头
      },
      success:res=>{
        console.log(res.data);
        this.setData({
          cartItems:res.data.data
        })
      },
      fail:err=>{
        console.log(err);
      }
    })
  },

  // 计算总价和选中数量
  calculateTotal() {
    const selectedItems = this.data.cartItems.filter(item => item.selected);
    const totalPrice = selectedItems.reduce((sum, item) => {
      return sum + (parseFloat(item.originprice) * item.num);
    }, 0);
    const selectedCount = selectedItems.reduce((sum, item) => sum + item.num, 0);

    this.setData({
      totalPrice: totalPrice.toFixed(2),
      selectedCount: selectedCount,
      selectAll: selectedItems.length === this.data.cartItems.length && this.data.cartItems.length > 0
    });
  },

  // 全选/取消全选
  toggleSelectAll() {
    const newSelectAll = !this.data.selectAll;
    const cartItems = this.data.cartItems.map(item => ({
      ...item,
      selected: newSelectAll
    }));

    this.setData({
      cartItems: cartItems,
      selectAll: newSelectAll
    });
    this.calculateTotal();
    wx.setStorageSync('cart', cartItems);
  },

  // 切换商品选中状态
  toggleProductSelect(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = [...this.data.cartItems];
    cartItems[index].selected = !cartItems[index].selected;

    this.setData({
      cartItems: cartItems
    });
    this.calculateTotal();
    wx.setStorageSync('cart', cartItems);
  },

  // 增加商品数量
  increaseQuantity(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = [...this.data.cartItems];
    cartItems[index].num += 1;

    this.setData({
      cartItems: cartItems
    });
    this.calculateTotal();
    wx.setStorageSync('cart', cartItems);
  },

  // 减少商品数量
  decreaseQuantity(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = [...this.data.cartItems];
    if (cartItems[index].num > 1) {
      cartItems[index].num -= 1;

      this.setData({
        cartItems: cartItems
      });
      this.calculateTotal();
      wx.setStorageSync('cart', cartItems);
    }
  },

  // 删除商品
  deleteProduct(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = [...this.data.cartItems];
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这个商品吗？',
      success: (res) => {
        if (res.confirm) {
          cartItems.splice(index, 1);
          this.setData({
            cartItems: cartItems
          });
          this.calculateTotal();
          wx.setStorageSync('cart', cartItems);
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 去购物
  goShopping() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 结算
  checkout() {
    if (this.data.selectedCount === 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none'
      });
      return;
    }

    wx.showToast({
      title: `结算${this.data.selectedCount}件商品，总价¥${this.data.totalPrice}`,
      icon: 'none',
      duration: 2000
    });
  }
});